package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"io"
	"os"
	"regexp"
	"strconv"
	"strings"
)

type MysqlConfig struct {
	Address  string `json:"address"`
	Port     int    `json:"port"`
	Username string `json:"username"`
	Password string `json:"password"`
}

func loadIni(v interface{}) {

}

func isInt(s string) bool {
	match, _ := regexp.MatchString(`^[\+-]?\d+$`, s)
	return match
}

func readFromFilebybufio() map[string]interface{} {
	fileObj, err := os.Open("./conf.ini")
	if err != nil {
		fmt.Printf("open file failed,err:%v \n", err)
	}

	//记得关闭文件
	defer fileObj.Close()
	//创建一个用来从文件中读内容的对象
	reader := bufio.NewReader(fileObj)
	sj := make(map[string]interface{}, 4)
	for {
		line, err := reader.ReadString('\n')
		line = strings.TrimSpace(line)
		if err == io.EOF {
			//fmt.Println(line)
			comma := strings.Index(line, "=")
			if comma >= 0 {
				//fmt.Println(line[:comma], line[comma+1:len(line)])
				if isInt(line[comma+1:]) {
					i, _ := strconv.Atoi(line[comma+1:])
					sj[line[:comma]] = i
				} else {
					sj[line[:comma]] = line[comma+1:]
				}

			} else {
				continue
			}
			fmt.Println("读完了")
			return sj
		}
		if err != nil {
			fmt.Printf("read line failed,err:%v\n", err)
		}

		//fmt.Println(len(line))
		comma := strings.Index(line, "=")
		//fmt.Println(comma)
		if comma >= 0 {
			//fmt.Println(line[:comma], line[comma+1:len(line)])
			if isInt(line[comma+1 : len(line)-1]) {
				i, _ := strconv.Atoi(line[comma+1:])
				sj[line[:comma]] = i
			} else {
				sj[line[:comma]] = line[comma+1:]
			}

		} else {
			continue
		}

	}

}

func main() {
	/* 	var mc MysqlConfig
	   	loadIni(&mc)
	   	fmt.Println(mc.Address, mc.Port, mc.Username, mc.Password) */
	ini := readFromFilebybufio()
	fmt.Println(ini)
	fmt.Printf("%T---%v \n", ini["address"], ini["address"])
	fmt.Printf("%T---%v \n", ini["port"], ini["port"])
	fmt.Printf("%T---%v \n", ini["username"], ini["username"])
	fmt.Printf("%T---%v \n", ini["password"], ini["password"])
	var conf MysqlConfig
	//str := `{"address":ini["address"],"port":ini["port"],"username":ini["username"],"password":ini["password"]}`
	//str := `{"address":"qwe","port":3306,"username":"wsx","password":"rfv"}`
	//json.Unmarshal([]byte(str), &conf)
	//fmt.Println(conf)

	arr, err := json.Marshal(ini)
	if err != nil {
		panic(err)
	}
	fmt.Printf("arr=%s \n", string(arr))
	//mString := string(arr)
	err1 := json.Unmarshal(arr, &conf)
	if err1 != nil {
		panic(err1)
	}
	fmt.Printf("%T---%v \n", conf.Port, conf.Port)
	fmt.Printf("%#v \n", conf)

	/* 	var conf MysqlConfig
	   	t := reflect.TypeOf(conf)
	   	for k, v := range ini {
	   		for i := 0; i < t.NumField(); i++ {
	   			field := t.Field(i)
	   			if k == field.Tag.Get("ini") {
	   				field.Name = strings(v)
	   			}
	   			fmt.Printf("name:%s  json tag:%v\n", field.Name, field.Tag.Get("ini"))
	   		}
	   	} */
}
